package com.kdtech.analyse.news;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.analyse.JSoupUtils;
import com.kdtech.crawler.CrawlHTML;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.StringUtils;
import com.kdtech.utils.HtmlCleaner;


public class SportseduNewsAnalyse implements AnalyseNews {

	private static final String[] regex={
		"http://www.sports.edu.cn/.*.aspx[?]kind=[0-9]*&pk=[0-9]*",
	};


	
	public boolean isDetailPage(String url) {
		for (int i=0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return false;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		String url = "";
		NewsMeta news=new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}
		String htmltxt=urlMeta.getHtml();
		urlMeta.getUrl();
		
		Matcher matcher = Pattern.compile("<iframe.*src=\"/news/([0-9]*).html\".*>",Pattern.CASE_INSENSITIVE).matcher(htmltxt);
		if(matcher.find()){
			String id = matcher.group(1);
			url = "http://www.sports.edu.cn/News/"+id+".html";
			urlMeta = CrawlHTML.responseToURL(url);
			if(urlMeta != null){
				htmltxt = urlMeta.getHtml();
			}
		}
		news.setUrl(url);
		String title=null;
		String content=null;
		String author=null;
		Long date=null;
		Document doc=Jsoup.parse(htmltxt);
		
		title=doc.select("div.main h2").text();
		date=DateUtils.matchDate(doc.select("div.main p.time").text());
		content =HtmlCleaner.getContentHtml(url, doc.select("div.content"));
		author=JSoupUtils.matchAuthor(doc, "来源：");
		news.setTitle(StringUtils.trimSpace(title));
		news.setAuthor(author);
		news.setContent(content);
		news.setDate(date);

		return news;

	}

	public static void main(String[] args) {
		SportseduNewsAnalyse analyse=new SportseduNewsAnalyse();
		String url="http://www.sports.edu.cn/xiangxi.aspx?pk=2548&kind=18";
		url = UrlArgumentTop.FromatUrl(url);
		System.out.println(UrlArgumentTop.FromatUrl(url));
		System.out.println(analyse.isDetailPage(url));
		UrlMeta meta=CrawlHTML.responseToURL(url);
		System.out.println(analyse.parserHtml(meta));
	}

	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}

	
	public boolean isNeedUpdate(){
		return false;
	}
}

